package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cssy.authority.dao.AppSqlConfig;
import com.cssy.authority.service.IAuthorityService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.authority.service.impl.AuthorityServiceImpl;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicProductionPlanDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageinDO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageinItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionPlanService;
import com.cssy.xxkj.logic.service.ILogicProductionStorageInService;
import com.cssy.xxkj.logic.util.OftenMapUtil;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;
/**
 * 生产入库控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/prostoragein")
public class ProductionStorageInController extends BaseController<LogicProductionStorageinDO> {
	
	private static final Logger logger = Logger.getLogger(ProductionStorageInController.class);

	private static final String MANAGER = "/xxkj/logic/prostoragein/ProStorageInManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/prostoragein/ProStorageInOperation";// 添加、修改、显示页面

	@Resource(name = "logicProductionStorageInService")
	private ILogicProductionStorageInService logicProductionStorageInService;
	
	@Resource(name = "logicProductionPlanService")
	private ILogicProductionPlanService logicProductionPlanService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;
	
	@Resource(name = "oftenMapUtil")
	private OftenMapUtil oftenMapUtil;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=this.oftenMothedUtil.getNoFinishConditions(scs, "zd011BillStatus", BillStatusUtil.PROSTORIN_STATUS_FIVE);
		if(StringUtils.isBlank(scs.getOrderBy())){
			scs.setOrderBy("bizCreatorDate desc");
		}
		Map<String, Object> whMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService, "zd004WhCode");
		scs.addCondition(whMap.get("option")+"",(List<String>)whMap.get("roleWhList"));
		SearchResult result = logicProductionStorageInService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("viewflag", "add");
			model.addAttribute("xx", 1);//标示能不能修改内容
		}else{
			LogicProductionStorageinDO oi = logicProductionStorageInService.findListById(id);
			if(StringUtils.isNotBlank(oi.getZd002OriCode())){
				SearchConditions planScs = new SearchConditions();
				planScs.addCondition("zd001FormCode", oi.getZd002OriCode(), SearchCondition.OP_EQUAL);
				List<LogicProductionPlanDO> planList = logicProductionPlanService.findListByExample(planScs).getResults();
				if(planList==null||planList.isEmpty()||planList.size()==0){
					model.addAttribute("xilie", "");
				}else{
					String xilie="";
					if(planList.get(0).getZd002OriType().equals("BT")){
						xilie="套床";
					}else if(planList.get(0).getZd002OriType().equals("MT")){
						xilie="床垫";
					}
					
					if(oi!=null&&StringUtils.isNotBlank(oi.getZd006Aegnt())){
						SqlMapClient sqlMapClient = AppSqlConfig.getSqlMapInstance();
						IAuthorityService ias = new AuthorityServiceImpl(sqlMapClient);
						com.cssy.authority.entity.User u = ias.getByUserName(oi.getZd006Aegnt());
						model.addAttribute("userName", u.getRealname());
					}
					model.addAttribute("xilie", xilie);
				}
			}
			model.addAttribute("oi", oi);
			if (oi.getZd011BillStatus().equals(BillStatusUtil.PROSTORIN_STATUS_ONE)||oi.getZd011BillStatus().equals(BillStatusUtil.PROSTORIN_STATUS_SIX)){
				model.addAttribute("xx", 1);//标示能不能修改内容
				model.addAttribute("viewflag", "tijiao");
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			if (oi.getZd011BillStatus().equals(BillStatusUtil.PROSTORIN_STATUS_FIVE)){
				model.addAttribute("viewflag", "tongguo");
			}
			if (oi.getZd011BillStatus().equals(BillStatusUtil.PROSTORIN_STATUS_TWO)){
				model.addAttribute("viewflag", "shenpi");
			}
		}
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionStorageinDO prodispat = logicProductionStorageInService.findListById(id);
			List<LogicProductionStorageinItemDO> soitem = logicProductionStorageInService.findStorInItemList(prodispat.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionStorageinDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("addressInfos");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionStorageInService.inSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionStorageinDO ld = logicProductionStorageInService.findListById(field);
				logicProductionStorageInService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping("/gridBomItems")
	public void gridBomItems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicProductionStorageinItemDO> inList = new ArrayList<LogicProductionStorageinItemDO>();
			LogicProductionPlanDO proplan = logicProductionPlanService.findListById(id);
			List<LogicProductionPlanItemDO> planitem = logicProductionPlanService.findPlanItemList(proplan.getId());
			if(planitem!=null&&!planitem.isEmpty()&&planitem.size()>0){
				inList=this.planToStorageIn(planitem,proplan);
			}
			OutJsonGrid out = new OutJsonGrid(inList);
			out.printJSon(response);
		}
	}
	
	private List<LogicProductionStorageinItemDO> planToStorageIn(List<LogicProductionPlanItemDO> planItemList,LogicProductionPlanDO proplan) throws Exception{
		List<LogicProductionStorageinItemDO> inList = new ArrayList<LogicProductionStorageinItemDO>();
		Map<String, BigDecimal> hasInQuantityMap = this.findQueryHasStorageInItemToMap(proplan.getZd001FormCode(), proplan.getZd003PiCode());
		for(int i=0; i<planItemList.size(); i++){
			LogicProductionPlanItemDO planItem = planItemList.get(i);
			LogicProductionStorageinItemDO inItem = new LogicProductionStorageinItemDO();
			String keyStr = proplan.getZd003PiCode()+"_"+proplan.getZd001FormCode()+"_"
					+planItem.getZd007MaterialsCode()+"_"+planItem.getZd038MaterialsSize()+"_"
					+planItem.getZd010MaterialsModel()+"_"+planItem.getZd042MaterialsQuality()+"_"
					+planItem.getZd041MaterialsColor();
			inItem.setZd002MaterialsCode(planItem.getZd007MaterialsCode());
			inItem.setZd002MaterialsId(planItem.getZd006MaterialsId());
			inItem.setZd002MaterialsName(planItem.getZd008MaterialsName());
			inItem.setZd003MaterialsSpec(planItem.getZd011MaterialsSpec());
			inItem.setZd004MaterialsModel(planItem.getZd010MaterialsModel());
			inItem.setZd006Unit(planItem.getZd012MaterialsUnit());
			inItem.setZd009Price(planItem.getZd017Price());
			inItem.setZd014MaterialsDescription(planItem.getZd036MaterialsDescription());
			inItem.setZd015MaterialsSize(planItem.getZd038MaterialsSize());
			inItem.setZd016MaterialsColor(planItem.getZd041MaterialsColor());
			inItem.setZd017MaterialsQuality(planItem.getZd042MaterialsQuality());
			inItem.setZd018PlanQuantity(planItem.getZd013Quantity());
			//总数
			BigDecimal sumQuantity = planItem.getZd013Quantity()==null?BigDecimal.ZERO:planItem.getZd013Quantity();
			//已入库数量
			if(hasInQuantityMap==null||hasInQuantityMap.get(keyStr)==null){
				inItem.setZd019WareQuantity(BigDecimal.ZERO);
				inItem.setZd007Quantity(sumQuantity);
			}else{
				inItem.setZd019WareQuantity(hasInQuantityMap.get(keyStr));
				inItem.setZd007Quantity(sumQuantity.subtract(hasInQuantityMap.get(keyStr)));
			}
			inList.add(inItem);
		}
		return inList;
	}
	
	/**
	 * 查询当前已入库的产品
	 */
	
	private Map<String, BigDecimal> findQueryHasStorageInItemToMap(String oriCode, String piCode)throws Exception{
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("piCode", piCode);
		paramMap.put("oriCode", oriCode);
		paramMap.put("billSt", BillStatusUtil.PROSTORIN_STATUS_FIVE);
		return logicProductionStorageInService.findStorageinItemToMap(paramMap);
	}
	
	@RequestMapping(value = "/updateState")
	@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String,String> map=new HashMap<String,String>();
		try{
			String ids = request.getParameter("rows");
			if(ids!=null&&!"".equals(ids)){
				LogicProductionStorageinDO lot=logicProductionStorageInService.findListById(ids);
				if(lot.getId()!=null){
					lot.setZd011BillStatus(BillStatusUtil.PROSTORIN_STATUS_SIX);
					logicProductionStorageInService.update(lot, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}
}
